<?php
/**
 * Created by PhpStorm.
 * User: Lin Hui
 * Date: 2017/5/19
 * Time: 17:07
 */

namespace Common\Lib;


use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class Qiniu
{
    /**
     * 返回七牛upToken
     * @return mixed
     * @author Lin Hui
     */
    public static function getToken()
    {
        // 构建鉴权对象
        $accessKey = C('QINIU.AccessKey');
        $secretKey = C('QINIU.SecretKey');
        $auth = new Auth($accessKey, $secretKey);
        $bucket = C('QINIU.bucket');
        // 生成上传Token
        $token = $auth->uploadToken($bucket);
        return $token;
    }

    /**
     * 七牛云服务器上传接口
     * @param $filePath
     * @param $key
     * @return array
     * @author Lin Hui
     */
    public static function QiniuUpload($filePath, $key)
    {
        //获得token
        $token = self::getToken();

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, C('QINIU.qiniu_url') . '/' . $key, $filePath);
        $res = ['status' => true, 'url' => C('QINIU.qiniu_url') . '/' . $key];
        $err_code = array(
            200 => '上传成功',
            400 => '请求报文格式错误',
            401 => '上传凭证无效',
            413 => '上传内容长度大于',
            579 => '回调业务服务器失败',
            599 => '服务端操作失败',
            614 => '目标资源已存在',
        );
        $msg = $err->message();
        if (!$msg) {
            $response = $err->getResponse();
            $msg = $err_code[$response->statusCode];
        }
        if (!$err == null) return ['status' => false, 'msg' => $msg];

        return $res;
    }

    /**
     *资源列表
     * @param string $extension
     * @return array
     */
    public static function _list($extension = '', $limit = 18, $mark = '')
    {
        $extension = strtolower($extension);
        // 构建鉴权对象
        $accessKey = C('QINIU.AccessKey');
        $secretKey = C('QINIU.SecretKey');
        $auth = new Auth($accessKey, $secretKey);
        $manage = new BucketManager($auth);
        list($list, $mark) = $manage->listFiles(C('QINIU.bucket'), C('QINIU.qiniu_url'), $mark, $limit);
        foreach($list as $key => $value) {
            if($extension && strpos($value['mimeType'], $extension) === false) {
                unset($list[$key]);
                continue;
            }
            $list[$key]['type'] = $extension;
        }
        return array($list, $mark);
    }

}